import 'dart:async';
import 'package:flutter/foundation.dart';
import '../models/models.dart';
import 'database_service.dart';
import 'music_library_service.dart';

/// 播放统计服务类
/// 负责管理播放统计数据的收集、分析和展示
class PlayStatisticsService extends ChangeNotifier {
  static final PlayStatisticsService _instance =
      PlayStatisticsService._internal();
  factory PlayStatisticsService() => _instance;
  PlayStatisticsService._internal();

  final DatabaseService _databaseService = DatabaseService();
  final MusicLibraryService _musicLibraryService = MusicLibraryService();

  PlayStatistics? _currentStatistics;
  bool _isLoading = false;

  // Getters
  PlayStatistics? get currentStatistics => _currentStatistics;
  bool get isLoading => _isLoading;

  /// 初始化播放统计服务
  Future<void> init() async {
    await loadStatistics();
  }

  /// 加载播放统计数据
  Future<void> loadStatistics() async {
    _isLoading = true;
    notifyListeners();

    try {
      if (kIsWeb) {
        // Web平台使用内存统计数据
        _currentStatistics = PlayStatistics(
          id: 'main_statistics',
          totalPlayTime: 0,
          totalPlayCount: 0,
          todayPlayTime: 0,
          todayPlayCount: 0,
          mostPlayedMusicIds: [],
          recentlyPlayedMusicIds: [],
          updatedAt: DateTime.now(),
        );
      } else {
        _currentStatistics = await _databaseService.getPlayStatistics();

        // 如果没有统计数据，创建默认的
        if (_currentStatistics == null) {
          _currentStatistics = PlayStatistics(
            id: 'main_statistics',
            totalPlayTime: 0,
            totalPlayCount: 0,
            todayPlayTime: 0,
            todayPlayCount: 0,
            mostPlayedMusicIds: [],
            recentlyPlayedMusicIds: [],
            updatedAt: DateTime.now(),
          );
          await _databaseService
              .insertOrUpdatePlayStatistics(_currentStatistics!);
        }
      }
    } catch (e) {
      debugPrint('加载播放统计失败: $e');
    } finally {
      _isLoading = false;
      notifyListeners();
    }
  }

  /// 记录播放行为
  Future<void> recordPlay({
    required String musicId,
    required int playDuration,
    bool isToday = true,
  }) async {
    try {
      if (kIsWeb) {
        // Web平台使用内存统计
        if (_currentStatistics != null) {
          final updatedMostPlayed =
              List<String>.from(_currentStatistics!.mostPlayedMusicIds);
          final updatedRecentPlayed =
              List<String>.from(_currentStatistics!.recentlyPlayedMusicIds);

          // 更新最近播放列表（保持最新的20首）
          updatedRecentPlayed.remove(musicId);
          updatedRecentPlayed.insert(0, musicId);
          if (updatedRecentPlayed.length > 20) {
            updatedRecentPlayed.removeRange(20, updatedRecentPlayed.length);
          }

          // 更新最常播放列表
          if (!updatedMostPlayed.contains(musicId)) {
            updatedMostPlayed.add(musicId);
          }

          _currentStatistics = _currentStatistics!.copyWith(
            totalPlayTime: _currentStatistics!.totalPlayTime + playDuration,
            totalPlayCount: _currentStatistics!.totalPlayCount + 1,
            todayPlayTime: isToday
                ? _currentStatistics!.todayPlayTime + playDuration
                : _currentStatistics!.todayPlayTime,
            todayPlayCount: isToday
                ? _currentStatistics!.todayPlayCount + 1
                : _currentStatistics!.todayPlayCount,
            mostPlayedMusicIds: updatedMostPlayed,
            recentlyPlayedMusicIds: updatedRecentPlayed,
            updatedAt: DateTime.now(),
          );
          notifyListeners();
        }
      } else {
        await _databaseService.incrementPlayStatistics(
          playTime: playDuration,
          musicId: musicId,
          isToday: isToday,
        );

        // 重新加载统计数据
        await loadStatistics();
      }
    } catch (e) {
      debugPrint('记录播放行为失败: $e');
    }
  }

  /// 获取最常播放的音乐列表
  Future<List<Music>> getMostPlayedMusic({int limit = 10}) async {
    if (_currentStatistics == null) return [];

    try {
      final musicList = <Music>[];
      final musicLibrary = _musicLibraryService.musicLibrary;

      // 根据播放次数排序音乐
      final sortedMusic = List<Music>.from(musicLibrary)
        ..sort((a, b) => b.playCount.compareTo(a.playCount));

      // 取前limit首
      musicList.addAll(sortedMusic.take(limit));

      return musicList;
    } catch (e) {
      debugPrint('获取最常播放音乐失败: $e');
      return [];
    }
  }

  /// 获取最近播放的音乐列表
  Future<List<Music>> getRecentlyPlayedMusic({int limit = 10}) async {
    if (_currentStatistics == null) return [];

    try {
      final musicList = <Music>[];
      final musicLibrary = _musicLibraryService.musicLibrary;

      for (final musicId
          in _currentStatistics!.recentlyPlayedMusicIds.take(limit)) {
        try {
          final music = musicLibrary.firstWhere((m) => m.id == musicId);
          musicList.add(music);
        } catch (e) {
          // 音乐可能已被删除，跳过
          continue;
        }
      }

      return musicList;
    } catch (e) {
      debugPrint('获取最近播放音乐失败: $e');
      return [];
    }
  }

  /// 获取播放时长统计
  Map<String, dynamic> getPlayTimeStatistics() {
    if (_currentStatistics == null) {
      return {
        'totalHours': 0,
        'totalMinutes': 0,
        'todayHours': 0,
        'todayMinutes': 0,
        'averagePerDay': 0,
        'averagePerSong': 0,
      };
    }

    final totalHours = _currentStatistics!.totalPlayTime ~/ 3600000;
    final totalMinutes = (_currentStatistics!.totalPlayTime % 3600000) ~/ 60000;
    final todayHours = _currentStatistics!.todayPlayTime ~/ 3600000;
    final todayMinutes = (_currentStatistics!.todayPlayTime % 3600000) ~/ 60000;

    // 计算平均每天播放时长（假设统计开始于30天前）
    final averagePerDay =
        _currentStatistics!.totalPlayTime ~/ (30 * 24 * 3600000);

    // 计算平均每首歌播放时长
    final averagePerSong = _currentStatistics!.totalPlayCount > 0
        ? _currentStatistics!.totalPlayTime ~/
            _currentStatistics!.totalPlayCount ~/
            60000
        : 0;

    return {
      'totalHours': totalHours,
      'totalMinutes': totalMinutes,
      'todayHours': todayHours,
      'todayMinutes': todayMinutes,
      'averagePerDay': averagePerDay,
      'averagePerSong': averagePerSong,
    };
  }

  /// 获取播放次数统计
  Map<String, int> getPlayCountStatistics() {
    if (_currentStatistics == null) {
      return {
        'totalCount': 0,
        'todayCount': 0,
        'averagePerDay': 0,
      };
    }

    // 计算平均每天播放次数（假设统计开始于30天前）
    final averagePerDay = _currentStatistics!.totalPlayCount ~/ 30;

    return {
      'totalCount': _currentStatistics!.totalPlayCount,
      'todayCount': _currentStatistics!.todayPlayCount,
      'averagePerDay': averagePerDay,
    };
  }

  /// 获取音乐类型分布统计
  Future<Map<String, int>> getGenreDistribution() async {
    try {
      final musicLibrary = _musicLibraryService.musicLibrary;
      final genreCount = <String, int>{};

      for (final music in musicLibrary) {
        final genre = music.genre ?? '未知';
        genreCount[genre] = (genreCount[genre] ?? 0) + music.playCount;
      }

      // 按播放次数排序
      final sortedGenres = genreCount.entries.toList()
        ..sort((a, b) => b.value.compareTo(a.value));

      return Map.fromEntries(sortedGenres);
    } catch (e) {
      debugPrint('获取音乐类型分布失败: $e');
      return {};
    }
  }

  /// 获取艺术家分布统计
  Future<Map<String, int>> getArtistDistribution() async {
    try {
      final musicLibrary = _musicLibraryService.musicLibrary;
      final artistCount = <String, int>{};

      for (final music in musicLibrary) {
        final artist = music.artist;
        artistCount[artist] = (artistCount[artist] ?? 0) + music.playCount;
      }

      // 按播放次数排序
      final sortedArtists = artistCount.entries.toList()
        ..sort((a, b) => b.value.compareTo(a.value));

      return Map.fromEntries(sortedArtists.take(10));
    } catch (e) {
      debugPrint('获取艺术家分布失败: $e');
      return {};
    }
  }

  /// 重置今日统计
  Future<void> resetTodayStatistics() async {
    try {
      if (kIsWeb) {
        // Web平台使用内存统计
        if (_currentStatistics != null) {
          _currentStatistics = _currentStatistics!.copyWith(
            todayPlayTime: 0,
            todayPlayCount: 0,
            updatedAt: DateTime.now(),
          );
          notifyListeners();
        }
      } else {
        await _databaseService.resetTodayStatistics();
        await loadStatistics();
      }
    } catch (e) {
      debugPrint('重置今日统计失败: $e');
    }
  }

  /// 清空所有统计数据
  Future<void> clearAllStatistics() async {
    try {
      if (kIsWeb) {
        // Web平台使用内存统计
        _currentStatistics = PlayStatistics(
          id: 'main_statistics',
          totalPlayTime: 0,
          totalPlayCount: 0,
          todayPlayTime: 0,
          todayPlayCount: 0,
          mostPlayedMusicIds: [],
          recentlyPlayedMusicIds: [],
          updatedAt: DateTime.now(),
        );
        notifyListeners();
      } else {
        await _databaseService.clearPlayStatistics();
        _currentStatistics = null;
        await loadStatistics();
      }
    } catch (e) {
      debugPrint('清空统计数据失败: $e');
    }
  }

  /// 导出统计数据
  Map<String, dynamic> exportStatistics() {
    if (_currentStatistics == null) return {};

    return {
      'statistics': _currentStatistics!.toJson(),
      'playTimeStats': getPlayTimeStatistics(),
      'playCountStats': getPlayCountStatistics(),
      'exportTime': DateTime.now().toIso8601String(),
    };
  }

  /// 获取统计摘要
  String getStatisticsSummary() {
    if (_currentStatistics == null) return '暂无统计数据';

    final timeStats = getPlayTimeStatistics();
    final countStats = getPlayCountStatistics();

    return '''
总播放时长: ${timeStats['totalHours']}小时${timeStats['totalMinutes']}分钟
总播放次数: ${countStats['totalCount']}次
今日播放: ${timeStats['todayHours']}小时${timeStats['todayMinutes']}分钟 (${countStats['todayCount']}次)
平均每首: ${timeStats['averagePerSong']}分钟
最常播放: ${_currentStatistics!.mostPlayedMusicIds.length}首音乐
最近播放: ${_currentStatistics!.recentlyPlayedMusicIds.length}首音乐
''';
  }
}
